//
//  WBMainViewController.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/5/29.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    //定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpNewFeatureViews()
        setUpChildControllers()
        setComposeButton()
        setUpTimer()
        delegate = self
        //测试未读数量
        WBNetworkManager.shared.unreadCount { (count) in
            print("有\(count)条新微博")
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        }
    }

    deinit {
        //销毁时钟
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    //portrait竖屏
    //landscape横屏
    /**
     --使用代码控制器设备横竖屏，可在需要横屏的时候，单独处理
     --设置支持的方向后，当前的控制器和子控制器都会遵守这个方向
     */
    /*
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
            UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        }
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(handleOrientationChange(notification:)),
                                               name:NSNotification.Name.UIApplicationDidChangeStatusBarOrientation,
                                               object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.removeObserver(self)
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
    }
    
    @objc private func handleOrientationChange(notification: Notification) {
        // 获取设备方向
        let statusBarOrientation = UIApplication.shared.statusBarOrientation
        if statusBarOrientation.isPortrait {
            print("竖屏了")
            
        } else if statusBarOrientation.isLandscape {
            print("横屏了")
            
        }
    }
    
//    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
//        coordinator.animate(alongsideTransition: { (_) in
//            let orient = UIApplication.shared.statusBarOrientation
//            if orient.isPortrait {
//                print("竖屏了")
//            } else if orient.isLandscape {
//                print("横屏了")
//            }
//
//        }) { (_) in
//            print("rotation completed")
//        }
//        super.willTransition(to: newCollection, with: coordinator)
//    }
 */
//    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask{
//
//        return .portrait
//    }
    
    //监听方法
    @objc func userLogin(n: Notification) {
        print("用户登录的通知\(n)")
        var deadline = DispatchTime.now()
        
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录！")
            deadline = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现登录控制器----通常会和UINavigationController通用
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    //private能够保护方法私有，仅在当前对象被使用
    //@objc 允许这个函数在‘运行时’通过‘OC’的消息机制被调用
    @objc private func composeAction(){
        print("加号按钮点击")
        //FIXME:0>判断是否登录
        //1>实例化视图
        let v = WBComposeTypeView.composeTypeView()
        //2>显示-注意闭包的循环引用
        v.show { [weak v] (clsName) in
            //撰写微博控制器
            guard let clsName = clsName, let cls = NSClassFromString(Bundle.main.nameSpace + "." +  clsName) as? UIViewController.Type else {
                v?.removeFromSuperview()
                return
            }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            // 让导航控制器强行更新约束， - 会直接更新所有自视图的约束
            // 提示：开发中如果发现不希望的布局约束和动画混在一起，应该向前寻找
            nav.view.layoutIfNeeded()
            
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
            
        }
        
    }
    //MARK:私有控件
    //撰写按钮
    private lazy var composeButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}

// MARK: - 新特性视图处理
extension WBMainViewController {
    //设置新特性视图
    private func setUpNewFeatureViews() {
        //0.判断是否登录
//        if !WBNetworkManager.shared.userLogin {
//            return
//        }
        //1.如果有更新，显示新特性，否则显示欢迎视图
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        //添加视图
        v.frame = view.bounds
        //3.添加视图
        view.addSubview(v)
    }
    
    
    /// extension中可以有计算型属性，计算型属性不暂用存储空间
    //构造函数：给属性分配空间
    private var isNewVersion: Bool {
        //1. 去当前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)
        //2.取保存在Document（iTunes会自行备份）（最理想是存储在偏好设置里面）目录中之前的版本号
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path = (docDir as NSString).appendingPathComponent("version")
        let sandBoxVersion = (try? String(contentsOfFile: path, encoding: .utf8)) ?? ""
        print("沙盒版本" + sandBoxVersion)
        //3.将当前版本号保存在沙盒
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //4.返回两个版本号是否一致
        return currentVersion != sandBoxVersion
//        return currentVersion == sandBoxVersion
    }
    
}
extension WBMainViewController: UITabBarControllerDelegate {
    
    /// 将要选择tabbarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        print("切换到\(viewController)控制器")
        //1>获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //2>判断当前索引是首页，同时idx也是首页，重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            //3>让表格滚动到首页
            //a>获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            //b>滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //4>刷新数据（使用延时刷新是为了表格先滚动到顶部，再进行数据刷新）
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            //清除tabItem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        //判断目标控制器是否是UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}

extension WBMainViewController {
    //定义时钟
    private func setUpTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    //时钟触发方法
    @objc private func updateTimer() {
        if !WBNetworkManager.shared.userLogin {
            return
        }
        WBNetworkManager.shared.unreadCount { (count) in
            print("检测到有\(count)条微博")
            //设置首页tabbarItem的BadgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
           //设置app的BadgeNumber UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


//extension类似于OC中的分类，在Swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个extension里面
//便于代码维护
//注意：和OC分类一样，extension中，不能定义属性
//MARK:设置界面
extension WBMainViewController
{
    //设置撰写按钮
    private func setComposeButton(){
        tabBar.addSubview(composeButton)
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        //CGRectInset正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
//        print("撰写按钮的宽度\(composeButton.frame)")
        composeButton.addTarget(self, action: #selector(composeAction), for: .touchUpInside)
    }
    
    //设置所有子控制器
    private func setUpChildControllers () {
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        //data一定会有内容
        //反序列化转化成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else {
                return
        }
        
        //遍历数组循环创建控制器
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controllers(dict: dict))
        }
        viewControllers = arrayM
    }
    
    //子控制器
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 子控制器
    private func controllers(dict: [String: Any]) -> UIViewController {
        //1.取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let visitorDict = dict["visitorInfo"] as? [String: String],
        
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? WBBaseViewController.Type else {
            return UIViewController()
        }
        //2.创建视图控制器
        let vc = cls.init()
        //设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict
        vc.title = title
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        //4.设置标题字体(大小)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .highlighted)
       //系统默认是12号字体，设置字体大小，要设置normal的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], for: .normal)
        //实例化导航控制器的时候，会调用push方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
